package org.luxor.commons.rabbitmq;

import org.luxor.commons.core.constant.BaseConst;
import org.luxor.commons.core.utils.Jackson2Utils;
import org.luxor.commons.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Mr.yan @date 2019/10/17
 */
@Component
public class RabbitMqHelper {
    private static final Logger log = LoggerFactory.getLogger(RabbitMqHelper.class);

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param exchangeName          交换器
     * @param routingKey            路由键
     * @param message               消息内容
     * @param token                 身份Token
     * @param expirationMilliSecond 消息过期时间(单位:毫秒)
     */
    public void sendMessage(String exchangeName, String routingKey, Object message, final String token, final Long expirationMilliSecond) {

        if (message != null && StringUtils.isNotBlank(routingKey)) {
            String messageJson = Jackson2Utils.toJson(message);
            log.info("发送消息: routingKey=[{}], message=[{}], token=[{}]", routingKey, messageJson, token);
            rabbitTemplate.convertAndSend(exchangeName, routingKey, messageJson, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    // 设置消息头
                    message.getMessageProperties().setHeader(BaseConst.TOKEN_NAME, token);
                    if (expirationMilliSecond != null) {
                        // 消息过期时间(单位:毫秒)
                        message.getMessageProperties().setExpiration(String.valueOf(expirationMilliSecond));
                    }
                    return message;
                }
            });
        }
    }
}
